// alidns
//gitee.com/liuyl162/utils/alidns
package alidns

import (
	"errors"
	"fmt"

	"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
)

type DnsRec struct {
	RecId string
	Type  string
	RR    string
	Val   string
	Dom   string
}

func (rec *DnsRec) String() string {
	return fmt.Sprintf("%s.%s[%s,%s]:%s", rec.RR, rec.Dom, rec.RecId, rec.Type, rec.Val)
}

//查询域名记录
func DnsQueryByRR(ak, sk, domain, rr string) (*DnsRec, error) {
	res, err := DnsList(ak, sk, domain)
	if err != nil {
		return nil, err
	}
	for _, r := range res {
		if r.RR == rr {
			return r, nil
		}
	}
	return nil, errors.New("NotExist")
}

//查询域名记录
func DnsQueryByRid(ak, sk, domain, rid string) (*DnsRec, error) {
	client, err := alidns.NewClientWithAccessKey("cn-hangzhou", ak, sk)
	reqRi := alidns.CreateDescribeDomainRecordInfoRequest()
	reqRi.RecordId = rid
	// reqRi.Domain = domain
	res, err := client.DescribeDomainRecordInfo(reqRi)
	if err == nil {
		return &DnsRec{res.RecordId, res.RR, res.Type, res.Value, domain}, nil
	}
	return nil, err
}

//添加a记录，添加成功后，rec.RecId为记录ID
func DnsAddRec(ak, sk string, rec *DnsRec) error {
	client, err := alidns.NewClientWithAccessKey("cn-hangzhou", ak, sk)
	req := alidns.CreateAddDomainRecordRequest()
	req.DomainName = rec.Dom
	req.RR = rec.RR
	req.Type = rec.Type
	req.Value = rec.Val
	res, err := client.AddDomainRecord(req)
	if err != nil {
		return err
	}
	rec.RecId = res.RecordId
	return nil
}

//更新域名指向ip
func DnsUpdate(ak, sk string, rec DnsRec) error {
	client, err := alidns.NewClientWithAccessKey("cn-hangzhou", ak, sk)
	reqUr := alidns.CreateUpdateDomainRecordRequest()
	reqUr.RR = rec.RR
	reqUr.RecordId = rec.RecId
	reqUr.Type = rec.Type
	reqUr.Value = rec.Val
	_, err = client.UpdateDomainRecord(reqUr)
	if err != nil {
		return err
	}
	return nil
}

//返回所有dns记录
func DnsList(ak, sk, domain string) ([]*DnsRec, error) {
	client, _ := alidns.NewClientWithAccessKey("cn-hangzhou", ak, sk)
	reqRi := alidns.CreateDescribeDomainRecordsRequest()
	reqRi.DomainName = domain
	reqRi.PageSize = "100"
	res, err := client.DescribeDomainRecords(reqRi)
	if err != nil {
		return nil, err
	}
	list := []*DnsRec{}
	for _, r := range res.DomainRecords.Record {
		list = append(list, &DnsRec{r.RecordId, r.Type, r.RR, r.Value, domain})
	}
	return list, nil
}
